package com.pur.zsms.foodmanage.food.service.impl;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

import javax.annotation.Resource;

import net.sf.cglib.beans.BeanCopier;

import org.apache.commons.beanutils.BeanUtils;
import org.springframework.stereotype.Service;

import com.pur.zsms.common.exception.GenericException;
import com.pur.zsms.common.support.PageController;
import com.pur.zsms.common.support.PaginationSupport;
import com.pur.zsms.common.util.CipherUtil;
import com.pur.zsms.common.util.PubFun;
import com.pur.zsms.foodmanage.food.dao.IFoodDao;
import com.pur.zsms.foodmanage.food.po.FoodMaterPo;
import com.pur.zsms.foodmanage.food.po.FoodPo;
import com.pur.zsms.foodmanage.food.po.FoodTypePo;
import com.pur.zsms.foodmanage.food.service.IFoodService;
import com.pur.zsms.foodmanage.food.vo.FoodMaterVo;
import com.pur.zsms.foodmanage.food.vo.FoodTypeVo;
import com.pur.zsms.foodmanage.food.vo.FoodVo;
import com.pur.zsms.matermanage.mater.po.ShoppingCartMaterPo;
import com.pur.zsms.matermanage.mater.vo.ShoppingCartMaterVo;
import com.pur.zsms.pmsnmanage.menu.po.MenuPo;
import com.pur.zsms.pmsnmanage.role.po.RolePo;
import com.pur.zsms.pmsnmanage.role.vo.RoleVo;
import com.pur.zsms.pmsnmanage.user.dao.IUserDao;
import com.pur.zsms.pmsnmanage.user.po.LdAddressPo;
import com.pur.zsms.pmsnmanage.user.po.UserPo;
import com.pur.zsms.pmsnmanage.user.po.UserRolePo;
import com.pur.zsms.pmsnmanage.user.service.IUserService;
import com.pur.zsms.pmsnmanage.user.vo.UserVo;
import com.pur.zsms.po.CashierOrderDetailPo;
import com.pur.zsms.po.CashierOrderPo;
import com.pur.zsms.po.ShoppingCartCashierPo;
import com.pur.zsms.vo.ShoppingCartCashierVo;

@Service("foodService")
public class FoodServiceImpl implements IFoodService {
	String msg = "";

	public String getMsg() {
		return msg;
	}

	public void setMsg(String msg) {
		this.msg = msg;
	}

	@Resource(name = "foodDao")
	private IFoodDao foodDaoImpl;

	public IFoodDao getFoodDaoImpl() {
		return foodDaoImpl;
	}

	public void setFoodDaoImpl(IFoodDao foodDaoImpl) {
		this.foodDaoImpl = foodDaoImpl;
	}

	public PaginationSupport listFood(PageController pageController, FoodVo foodVo) throws GenericException {
		return foodDaoImpl.listFood(pageController, foodVo);
	}

	public PaginationSupport listFoodForCashier(PageController pageController, FoodVo foodVo) throws GenericException {
		return foodDaoImpl.listFoodForCashier(pageController, foodVo);

	}

	public List<Object[]> listFoodForCashier(FoodVo foodVo) throws GenericException {
		return foodDaoImpl.listFoodForCashier(foodVo);
	}

	public PaginationSupport listFoodIndex(PageController pageController, FoodVo foodVo) throws GenericException {
		return foodDaoImpl.listFoodIndex(pageController, foodVo);
	}

	public PaginationSupport listFoodMaterDetailed(PageController pageController, FoodMaterVo foodMaterVo) throws GenericException {
		return foodDaoImpl.listFoodMaterDetailed(pageController, foodMaterVo);

	}

	public PaginationSupport findShoppingCartCashier(PageController pageController, ShoppingCartCashierVo c) throws GenericException {
		return foodDaoImpl.findShoppingCartCashier(pageController, c);
	}

	public PaginationSupport getShoppingCartOrderTable(PageController pageController, ShoppingCartCashierVo tShoppingCartCashierVo)
			throws GenericException {
		return foodDaoImpl.getShoppingCartOrderTable(pageController, tShoppingCartCashierVo);

	}

	public int addFood(FoodVo c) throws GenericException {

		FoodPo po = new FoodPo();
		try {
			BeanUtils.copyProperties(po, c);
		} catch (Exception e) {
			e.printStackTrace();
			throw new RuntimeException("输入参数有误!");
		}
		return foodDaoImpl.addFood(po);
	}

	public void addFoodType(FoodTypeVo c) throws GenericException {
		FoodTypePo po = new FoodTypePo();
		try {
			BeanUtils.copyProperties(po, c);
		} catch (Exception e) {
			e.printStackTrace();
			throw new RuntimeException("输入参数有误!");
		}
		foodDaoImpl.addFoodType(po);
	}

	public String addFoodCheck(FoodVo c) throws GenericException {
		List<FoodPo> foodPoList = null;
		foodPoList = foodDaoImpl.findFoodPo(c);
		if (foodPoList == null || foodPoList.size() == 0) {
			return "0000";
		} else {
			return "0003";
		}
	}

	public void addFoodMater(List<FoodMaterVo> foodMaterVoList) throws GenericException {

		// 删除
		foodDaoImpl.deleteFoodMaterPo(foodMaterVoList.get(0).getFoodId());

		// 增加
		for (FoodMaterVo c : foodMaterVoList) {
			FoodMaterPo po = new FoodMaterPo();
			try {
				BeanUtils.copyProperties(po, c);
			} catch (Exception e) {
				e.printStackTrace();
				throw new RuntimeException("输入参数有误!");
			}
			foodDaoImpl.addFoodMater(po);
		}
	}

	public void updateFood(FoodVo c) throws GenericException {
		FoodPo tFoodPo = new FoodPo();
		BeanCopier copier = BeanCopier.create(FoodVo.class, FoodPo.class, false);
		copier.copy(c, tFoodPo, null);
		foodDaoImpl.updateFood(tFoodPo);

	}

	public FoodVo getFoodid(String c) throws GenericException {
		FoodPo foodPo = foodDaoImpl.listFoodByFoodName(c);
		FoodVo foodVo = new FoodVo();
		foodVo.setFoodId(foodPo.getFoodId());
		foodVo.setFoodMname(foodPo.getFoodMname());
		foodVo.setFoodMtype(foodPo.getFoodMtype());
		foodVo.setFoodMweight(foodPo.getFoodMweight());
		foodVo.setFoodName(foodPo.getFoodName());
		foodVo.setFoodType(foodPo.getFoodType());
		foodVo.setFoodType1(Integer.valueOf(foodPo.getFoodType1()));

		return foodVo;
	}

	public void updateUser(UserVo c) throws GenericException {
		UserPo po = new UserPo();
		try {
			BeanUtils.copyProperties(po, c);
			// MD5对用户密码加密
			CipherUtil cipher = new CipherUtil();
			String md5Pwd = cipher.generatePassword(po.getPassword());
			po.setPassword(md5Pwd);
		} catch (Exception e) {
			throw new RuntimeException("更新失败!");
		}
		po.setUpdateTime(PubFun.getCurrentDate());
		foodDaoImpl.updateUser(po);
	}

	public void deleteFood(int foodId) throws GenericException {
		foodDaoImpl.deleteFood(foodId);
	}

	public void deleteShoppingCartCashierPo(ShoppingCartCashierVo c) throws GenericException {
		foodDaoImpl.deleteShoppingCartCashierPo(c);
	}

	public void deleteShoppingCartOne(ShoppingCartCashierVo c) throws GenericException {
		List<ShoppingCartCashierPo> listPo = foodDaoImpl.getShoppingCartCashierPo(c);
		if (listPo != null && listPo.size() > 0) {
			ShoppingCartCashierPo po = listPo.get(0);
			if (po.getNumber().compareTo(new BigDecimal(1)) == 0) {
				foodDaoImpl.deleteShoppingCartCashierPo(c);
			} else if (po.getNumber().compareTo(new BigDecimal(1)) > 0) {
				po.setNumber(po.getNumber().subtract(new BigDecimal(1)));
				po.setFoodValueAll(po.getFoodValue().multiply(po.getNumber()));
				foodDaoImpl.updateShoppingCartCashierPo(po);
			}
		}
	}

	public UserVo listUserByUserId(String userId) throws GenericException {
		UserPo po = null;
		po = foodDaoImpl.listUserByUserId(userId);
		UserVo vo = new UserVo();
		try {
			BeanUtils.copyProperties(vo, po);
		} catch (Exception e) {
			throw new RuntimeException("查询失败!");
		}

		return vo;
	}

	public List<RoleVo> listRoleByUserId(String userId) throws GenericException {

		return null;
	}

	public void updateRoleByUserId(String userId, String[] roles) throws GenericException {
		List<UserRolePo> userRoleList = foodDaoImpl.listUserRoleByUserId(userId);
		List<UserRolePo> shouldRemoveList = userRoleList;
		List<UserRolePo> shouldUpdateList = new ArrayList<UserRolePo>();
		List<UserRolePo> shouldAddList = new ArrayList<UserRolePo>();
		if (roles != null) {
			for (String roleId : roles) {
				UserRolePo userRolePo = new UserRolePo();
				userRolePo.setRoleId(Long.parseLong(roleId.trim()));
				int i = 0;
				for (i = 0; i < userRoleList.size(); i++) {
					UserRolePo oldUserRolePo = userRoleList.get(i);
					if (userRolePo.getRoleId() == oldUserRolePo.getRoleId()) {
						userRolePo = oldUserRolePo;
						shouldRemoveList.remove(i);
						break;
					}
				}
				userRolePo.setUserId(Long.parseLong(userId));
				if (i == userRoleList.size()) { // 新用户角色
					userRolePo.setInsertTime(new Date());
					shouldAddList.add(userRolePo);
				} else {
					userRolePo.setUpdateTime(new Date());
					shouldUpdateList.add(userRolePo);
				}

			}
		}

		for (int i = 0; i < shouldRemoveList.size(); i++) {
			UserRolePo userRolePo = shouldRemoveList.get(i);
			foodDaoImpl.deleteUserRole(String.valueOf(userRolePo.getUserRoleId()));
		}

		for (int i = 0; i < shouldUpdateList.size(); i++) {
			UserRolePo userRolePo = shouldUpdateList.get(i);
			foodDaoImpl.updateUserRole(userRolePo);
		}

		for (int i = 0; i < shouldAddList.size(); i++) {
			UserRolePo userRolePo = shouldAddList.get(i);
		}
	}

	public UserPo findUserLogon(String userName, String password) throws GenericException {
		// TODO Auto-generated method stub
		return foodDaoImpl.findUserLogon(userName, password);
	}

	public List<MenuPo> getUserMenuList(String userId) throws GenericException {
		java.util.List<MenuPo> pvList = foodDaoImpl.getUserMenuList(userId);
		// rootList 存放parentId=0的菜单项，也就是没有父节点
		java.util.List<MenuPo> rootList = new java.util.ArrayList<MenuPo>();
		// allPvMap 存放所有的菜单项
		java.util.Map<String, MenuPo> allPvMap = new java.util.HashMap<String, MenuPo>();
		// restPvMap存放除了parentId=0的菜单项,LinkedHashMap保证顺序
		java.util.Map<String, MenuPo> restPvMap = new java.util.LinkedHashMap<String, MenuPo>();
		for (MenuPo view : pvList) {
			String parentId = view.getParentMenuId() + "";
			if (parentId.equals("0")) {
				rootList.add(view);
			} else {
				restPvMap.put(view.getMenuId() + "", view);
			}
			allPvMap.put(view.getMenuId() + "", view);
		}

		// 循环restPvMap，根据其父节点Id(parentId)从allPvMap找,如果存在则添加为父节点的子节点
		java.util.Iterator it = restPvMap.values().iterator();
		while (it.hasNext()) {
			MenuPo view = (MenuPo) it.next();
			String parentId = view.getParentMenuId() + "";
			if (allPvMap.containsKey(parentId)) {
				allPvMap.get(parentId).getSubPurview().add(view);
			}
		}
		return rootList;
	}

	public List<RoleVo> listAllRole() throws GenericException {

		return null;
	}

	@Override
	public String getFoodMaterId(String c) throws GenericException {
		List<Object[]> list;
		list = foodDaoImpl.getFoodMaterId(c);
		String checkBoxs = "";
		for (Object[] checkbox : list) {
			checkBoxs += "|" + checkbox[0].toString() + "-" + checkbox[1].toString();
		}
		if (checkBoxs.length() > 0) {
			checkBoxs = checkBoxs.substring(1);
		}
		return checkBoxs;
	}

	public List<FoodTypePo> getFoodType(FoodTypeVo c) throws GenericException {

		return foodDaoImpl.getFoodType(c);
	}

	public boolean addShoppingCartCashier(ShoppingCartCashierVo c) throws GenericException {

		ShoppingCartCashierPo po = new ShoppingCartCashierPo();
		// 先查看购物车中是否有新增商品
		List<ShoppingCartCashierPo> listShoppingCartCashierPo = foodDaoImpl.getShoppingCartCashierPo(c);
		if (listShoppingCartCashierPo != null && listShoppingCartCashierPo.size() > 0) {
			po = listShoppingCartCashierPo.get(0);
			po.setNumber(po.getNumber().add(new BigDecimal(1)));
			po.setFoodValueAll(po.getNumber().multiply(po.getFoodValue()));
			foodDaoImpl.updateShoppingCartCashierPo(po);
		} else {
			po.setCartId(c.getCartId());
			po.setFoodId(c.getFoodId());
			po.setFoodName(c.getFoodName());
			po.setFoodValue(c.getFoodValue());
			po.setNumber(c.getNumber());
			po.setShopId(c.getShopId());
			po.setFoodValueAll(c.getFoodValue());
			foodDaoImpl.addShoppingCartCashierPo(po);
		}
		return true;
	}

	public boolean updateShoppingCartCashier(ShoppingCartCashierVo c) throws GenericException {
		int cartId_new = c.getCartId();
		// 校验
		List<ShoppingCartCashierPo> listShoppingCartCashierPoCheck = foodDaoImpl.getShoppingCartCashierPo(c);
		if (listShoppingCartCashierPoCheck != null && listShoppingCartCashierPoCheck.size() > 0) {
			msg = "系统已有单号，请重新设置单号！";
			return false;
		}

		// 校验通过
		c.setCartId(0);
		ShoppingCartCashierPo po = new ShoppingCartCashierPo();
		List<ShoppingCartCashierPo> listShoppingCartCashierPo = foodDaoImpl.getShoppingCartCashierPo(c);
		for (ShoppingCartCashierPo shoppingCartCashierPo : listShoppingCartCashierPo) {
			shoppingCartCashierPo.setCartId(cartId_new);
			foodDaoImpl.updateShoppingCartCashierPo(shoppingCartCashierPo);
		}
		return true;
	}

	public List<Object[]> getShoppingCartCasherTotalValue(ShoppingCartCashierVo c) throws GenericException {
		return foodDaoImpl.getShoppingCartCasherTotalValue(c);
	}

	public List<Object[]> getCartOrderNumber(long shopId) throws GenericException {
		return foodDaoImpl.getCartOrderNumber(shopId);

	}

	public boolean receiptCommit(ShoppingCartCashierVo c) throws GenericException {
		// 校验总价格
		List<Object[]> listObject = foodDaoImpl.getShoppingCartCasherTotalValue(c);

		if (listObject != null && listObject.size() > 0 && listObject.get(0) != null) {
			Object a = listObject.get(0);

			BigDecimal value1 = new BigDecimal(a.toString());
			BigDecimal value2 = new BigDecimal(c.getFoodValueAllCheck());
			if (value1.compareTo(value2) != 0) {
				msg = "价格有问题！";
				return false;
			}
		} else {
			msg = "购物车价格为0！提交失败！";
			return false;
		}
		// 校验完毕 销售数据存入
		CashierOrderPo poCashierOrderPo = new CashierOrderPo();
		poCashierOrderPo.setOrderValue(c.getFoodValueAllCheck());
		poCashierOrderPo.setPayWay(c.getPayWay());
		poCashierOrderPo.setShopId(c.getShopId());
		poCashierOrderPo.setSubmitTime(PubFun.getCurrentDate() + " " + PubFun.getCurrentTime());
		poCashierOrderPo.setUserId(c.getUserId());
		foodDaoImpl.addCashierOrderPo(poCashierOrderPo);

		List<ShoppingCartCashierPo> listShoppingCartCashierPo = foodDaoImpl.getShoppingCartCashierPo(c);
		for (ShoppingCartCashierPo shoppingCartCashierPo : listShoppingCartCashierPo) {
			CashierOrderDetailPo po = new CashierOrderDetailPo();
			po.setCashierId(poCashierOrderPo.getCashierId());
			po.setFoodId(shoppingCartCashierPo.getFoodId());
			po.setFoodNumber(shoppingCartCashierPo.getNumber().toString());
			po.setFoodValue(shoppingCartCashierPo.getFoodValue().toString());
			foodDaoImpl.addCashierOrderDetailPo(po);
		}
		foodDaoImpl.deleteShoppingCartCashierPo(c);

		return true;
	}

	public String pulldownFoodTypeForShop(long shopId, String space) throws GenericException {
		FoodTypeVo tFoodTypeVo = new FoodTypeVo();
		tFoodTypeVo.setShopId(shopId);
		List<FoodTypePo> foodTypePolist = foodDaoImpl.getFoodType(tFoodTypeVo);
		StringBuffer jsonFoodType = new StringBuffer("");

		if (foodTypePolist != null && foodTypePolist.size() > 0) {

			jsonFoodType.append("[");
			if ("0".equals(space)) {
				jsonFoodType.append("{\"");
				jsonFoodType.append("foodType");
				jsonFoodType.append("\":\"");
				jsonFoodType.append("0");
				jsonFoodType.append("\",\"foodTypeName\":\"");
				jsonFoodType.append("全部");
				jsonFoodType.append("\"},");
			}

			for (FoodTypePo foodTypePo : foodTypePolist) {
				jsonFoodType.append("{\"");
				jsonFoodType.append("foodType");
				jsonFoodType.append("\":\"");
				jsonFoodType.append(foodTypePo.getFoodTypeId());
				jsonFoodType.append("\",\"foodTypeName\":\"");
				jsonFoodType.append(foodTypePo.getFoodTypeName());
				jsonFoodType.append("\"},");
			}
			jsonFoodType = new StringBuffer(jsonFoodType.substring(0, jsonFoodType.length() - 1));
			jsonFoodType.append("]");
		}
		return jsonFoodType.toString();
	}

	public List<FoodPo> getFoodPo(FoodVo c) throws GenericException {
		return foodDaoImpl.getFoodPo(c);
	}

}
